package com.itheima.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Course;
import com.itheima.domain.store.Question;
import com.itheima.service.store.CatalogService;
import com.itheima.service.store.CourseService;
import com.itheima.service.store.impl.CatalogServiceImpl;
import com.itheima.service.store.impl.CourseServiceImpl;
import com.itheima.utils.Log4jTest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * CatalogServlet
 * 2021/10/16 21:22
 * created by yangyawen
 */
@WebServlet(urlPatterns = "/store/catalog")
public class CatalogServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 1.获取参数
        String operation = request.getParameter("operation");
        if ("list".equals(operation)) {
            list(request, response);
        } else if ("toAdd".equals(operation)) {
            toAdd(request, response);
        } else if ("save".equals(operation)) {
            save(request, response);
        } else if ("toEdit".equals(operation)) {
            toEdit(request, response);
        } else if ("edit".equals(operation)) {
            edit(request, response);
        } else if ("delete".equals(operation)) {
            delete(request, response);
        }
    }

    /**
     * 删除
     *
     * @param request
     * @param response
     */
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过catalogId查询类型是否关联
        String catalogId = request.getParameter("id");
        List<Question> questionAndCatalog=findQuestionAndCatalog(catalogId);
        // 判断是否有关联表
        if (questionAndCatalog.size()==0){
            // 调用service
            catalogService.deleteCatalog(catalogId);//result为true说明删除成功
        }else {
            Log4jTest.logger.info("当前类型id为："+catalogId+"因为有关联的题目表，导致无法删除");
        }
        // 数据响应
        request.getRequestDispatcher(request.getContextPath() + "/store/catalog?operation=list").forward(request, response);
    }



    private List<Question> findQuestionAndCatalog(String catalogId) {
        List<Question> questionList = catalogService.findQuestionAndCatalog(catalogId);
        return questionList;
    }


    /**
     * 保存修改
     *
     * @param request
     * @param response
     */
    private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String id = request.getParameter("id");
        String courseId = request.getParameter("courseId");
        Course course = courseService.findCourseById(courseId);
        String courseName = course.getName();

        String name = request.getParameter("name");
        String state = request.getParameter("state");
        String remark = request.getParameter("remark");


        Catalog catalog = new Catalog();
        catalog.setId(id);
        catalog.setName(name);
        catalog.setState(state);
        catalog.setRemark(remark);
        catalog.setCourseName(courseName);
        catalog.setCourseId(courseId);
        // 调用service
        CatalogService catalogService = new CatalogServiceImpl();
        catalogService.updateCatalog(catalog);
        // 数据响应，跳转到页面list
        list(request, response);

    }

    /**
     * 返回编辑页面
     *
     * @param request
     * @param response
     */
    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String id = request.getParameter("id");
        // 调用service
        CatalogService catalogService = new CatalogServiceImpl();
        Catalog catalog = catalogService.findCatalogById(id);
        // 数据响应
        request.setAttribute("catalog", catalog);

        // 加学科信息
        CourseService courseService = new CourseServiceImpl();
        List<Course> courseList = courseService.findAll();
        // 响应数据
        request.setAttribute("courseList", courseList);

        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/store/catalog/update.jsp").forward(request, response);
    }

    /**
     * 添加
     *
     * @param request
     * @param response
     */
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
       String courseId = request.getParameter("courseId");
        Course course = courseService.findCourseById(courseId);
        // courseName要通过courseId获取
        if (course == null ){
            System.out.println("学科为空，无法保存");
            list(request, response);
        } else {
            String courseName = course.getName();

            String name = request.getParameter("name");
            String state = request.getParameter("state");
            String remark = request.getParameter("remark");
            // 新建catalog对象
            Catalog catalog = new Catalog();
            // 防止重名
            String id = UUID.randomUUID().toString();
            // 封装
            catalog.setId(id);
            catalog.setName(name);
            catalog.setState(state);
            catalog.setRemark(remark);
            catalog.setCourseName(courseName);
            catalog.setCourseId(courseId);
            // 调用service
            CatalogService catalogService = new CatalogServiceImpl();
            catalogService.addCatalog(catalog);
            // 数据响应
            list(request, response);
        }
    }

    /**
     * 返回添加
     *
     * @param request
     * @param response
     */
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 加学科信息
        List<Course> courseList = courseService.findAll();

        // 响应数据
        request.setAttribute("courseList", courseList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/store/catalog/add.jsp").forward(request, response);
    }


    /**
     * 查询全部，有分页的效果
     *
     * @param request
     * @param response
     */
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.获取参数
        String pageNum = request.getParameter("page");
        // 2.调用service层
        CatalogService catalogService = new CatalogServiceImpl();
        PageInfo page = catalogService.findByPage(pageNum);
        // 3.响应数据
        request.setAttribute("page", page);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/store/catalog/list.jsp").forward(request, response);
    }
}